package cn.shangqizhenshuai.sqiot.mqtt;

import cn.shangqizhenshuai.sqiot.Serivce.EquipmentService;
import cn.shangqizhenshuai.sqiot.entity.Equipment;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
@Repository("mqttStarter")
public class MqttStarter extends Thread {
    @Autowired
    @Qualifier("mqttservice")
    Mqttservice mqttservice;
    @Autowired
    @Qualifier("equipmentService")
    private EquipmentService equipmentService;
    @Autowired
    MyMqttCallBack myMqttCallBack;

    public Logger log = Logger.getLogger(MqttStarter.class);
    @Override
    public void run() {

        mqttservice.start(myMqttCallBack);
        //订阅频道
        String[] topic = this.getlist();
        int[] qoss= new int[topic.length];
        for (int i = 0; i < qoss.length; i++) {
            qoss[i]=2;
        }
        boolean sub = mqttservice.sub(topic, qoss);
    }

    /**
     * 开启服务时获取设备状态监听列表
     * @return
     */
    public String[] getlist(){
        List<Equipment> list = equipmentService.get_list();
        ArrayList<String> arrayList = new ArrayList<>();
        for (Equipment equipment : list) {
            arrayList.add(equipment.getStatrurl());
        }
        String[] strings = new String[arrayList.size()];
        return  arrayList.toArray(strings);
    }

    /**
     * 推送消息
     * @param topic 订阅地址
     * @param message 发送消息
     * @param Qos 级别
     * @return
     */
    public boolean pub(String topic ,String  message,int Qos){
        return mqttservice.pub("test", "OK", 1);
    }

    /**
     * 设置开启mqtt服务参数
     * @param HOST mqtt服务地址
     * @param clientid 客户端标识id
     * @param userName 用户名
     * @param passWord 密码
     * @param willtopic 断开连接时发送的消息地址(为null时不开启断开连接消息)
     * @param willpayload  断开消息内容(为null时不开启断开连接消息)
     * @param willqos 断开消息级别(为null时不开启断开连接消息)
     * @param willretainedd 是否保留这个断开消息(为null时不开启断开连接消息)
     * @param startTopic 启动成发送的消息（为null是不设置启动消息）
     * @param startPayload 启动成功发送的消息（为null是不设置启动消息）
     * @param startlQos 启动消息级别（为null是不设置启动消息）
     * @param automaticReconnection 是否自动重连 默认false
     * @param cleanSession  是否保持session，true无法接受离线消息， false可以接受离线消息 默认true
     * @param connectionTimeout 连接超时时间（秒） 默认30
     * @param keepAliveInterval 心跳时间（秒） 默认60
     * @param version 可选版本3.0 3.1.1 默认3.1.1
     */
    public void setstartinfo(String HOST,String clientid,String userName,String passWord,String willtopic,String willpayload,Integer willqos,Boolean willretainedd,String startTopic,String startPayload,Integer startlQos,Boolean automaticReconnection,Boolean cleanSession,Integer connectionTimeout,Integer keepAliveInterval,String version){
        if (StringUtils.isNotEmpty(HOST)) {
            mqttservice.setHOST(HOST);
            if (StringUtils.isNotEmpty(clientid)) {
                mqttservice.setClientid(clientid);

            } else {
                mqttservice.setClientid("sqiot");
            }

            if (StringUtils.isNotEmpty(userName)) {
                mqttservice.setUserName(userName);
            } else {
                log.error("启动用户名为空");

            }
            if (StringUtils.isNotEmpty(passWord)) {
                mqttservice.setPassWord(passWord);

            } else {
                log.error("启动密码为空");

            }
            if(StringUtils.isNotEmpty(willtopic)&&StringUtils.isNotEmpty(willpayload)&&willqos!=null&&willretainedd!=null){
                mqttservice.setWill(willtopic,willpayload,willqos,willretainedd);
            }
            if(StringUtils.isNotEmpty(startTopic)&&StringUtils.isNotEmpty(startPayload)&&startlQos!=null){
                mqttservice.setState(startTopic,startPayload,startlQos);
            }
            if(automaticReconnection==null){
                mqttservice.setAutomaticReconnection(false);
            }else{
                mqttservice.setAutomaticReconnection(automaticReconnection);
            }
            if (cleanSession == null) {
                mqttservice.setCleanSession(true);
            } else {
                mqttservice.setCleanSession(cleanSession);
            }
            if(connectionTimeout==null){
                mqttservice.setConnectionTimeout(30);
            }else{
                mqttservice.setConnectionTimeout(connectionTimeout);

            }
            if (keepAliveInterval == null) {
                mqttservice.setKeepAliveInterval(60);
            } else {
                mqttservice.setKeepAliveInterval(keepAliveInterval);
            }
            if (StringUtils.isNotEmpty(version)) {
                mqttservice.setVersion(version);

            } else {
                mqttservice.setVersion("3.1.1");

            }

        } else {
            log.error("未设置启动连接地址请设置后在重新启动mqtt服务");
        }

    }

    /**
     * 当前服务运行状态
     * @return
     */
    public boolean clientstate (){
       return  mqttservice.clientstate();
    }

    /**
     * 关闭消息
     * @return
     */
    public boolean shutdown() {
        return  mqttservice.shutdown();

    }

}
